<?php

use Drupal\s_announcement\Entity\SAnnouncement;

function s_announcement_s_announcement_entity_form($form, &$form_state, SAnnouncement $e, $op) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 's_announcement') . '/s_announcement.forms.inc';
  $form_state[SAnnouncement::class] = $e;


  $form['title'] = [
    '#title' => t('标题'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#default_value' => $e->title,
  ];
  $form['body'] = [
    '#type' => 'text_format',
    '#title' => t('公告内容'),
    '#default_value' => $e->body,
    '#format' => $e->format,
    '#rows' => 20,
  ];
  $form['sticky'] = [
    '#type' => 'checkbox',
    '#title' => t('显示在首页'),
    '#default_value' => $e->sticky,
  ];
  $form['status'] = [
    '#type' => 'checkbox',
    '#title' => t('开启'),
    '#default_value' => $e->status,
  ];

  field_attach_form($e->entityType(), $e, $form, $form_state);

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];
  return $form;
}

function s_announcement_s_announcement_entity_form_submit($form, &$form_state) {
  $e = $form_state[SAnnouncement::class];
  if ($e instanceof SAnnouncement) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->body = $form_state['values']['body']['value'];
    $e->format = $form_state['values']['body']['format'];
    $e->save();
  }
}

function s_announcement_s_announcement_delete_form($form, &$form_state, SAnnouncement $e) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 's_announcement') . '/s_announcement.forms.inc';
  $form_state[SAnnouncement::class] = $e;
  return confirm_form($form,
    t('Are you sure you want to delete %title?', ['%title' => $e->label()]),
    'admin/content/s_announcement/' . $e->id,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

function s_announcement_s_announcement_delete_form_submit($form, &$form_state) {
  $e = $form_state[SAnnouncement::class];
  if ($e instanceof SAnnouncement) {
    $e->delete();
  }
}

